const baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1/"

let ajaxConter = 0;

//使用Promise
const request = function (opations) {
  ajaxConter++;
  wx.showLoading({
    title: '加载数据...',
    mask:true
  })


  opations.url = baseUrl+opations.url
  
  return new Promise((resolve, reject) => {
    wx.request({
      ...opations,
      timeout: 5000,
      success: (result) => {
        resolve(result)
      },
      fail: (err) => {
        reject(err)
      },
      complete:()=>{
        //在全局自定义一个ajaxConter计数器，来表示某一时段一共发送了多少个ajax
        //每发送一个ajax就让conter++
        //每完成一个ajax，就让conter--
        //当conter为0的时候 则表示目前时段没有要发送和等待接受的请求 然后再去关闭loading效果
        ajaxConter--;
        if(ajaxConter === 0){
          wx.hideLoading()
        }

      }
    })
  })


}

//封装首页API
const homeApi = {
  getSwiperData:function(){
      return request({
        url:"home/swiperdata",
      })
  },
  //home/catitems
  getCatitems:function(){
    return request({
      url:"home/catitems",
    })
  },
  //home/floordata
  getFloorData:function(){
    return request({
      url:"home/floordata",
    })
  }
}

//封装分类API
const categoriesApi = {
  getCategories:function(){
    return request({
      url:"categories",
    })
  }
}


const goodsApi = {
  //商品列表
  getGoodsList:function(data){
    return request({
      url:"goods/search",
      data:data
    })
  },

  //商品列表
  getGoodsDetail:function(data){
    return request({
      url:"goods/detail",
      data:data
    })
  },

  //商品列表搜索
  getGoodsSearch:function(data){
    return request({
      url:"goods/qsearch",
      data:data
    })
  },
}


const usersApi = {
  //获取token值
  wxlogin: function(data){
        return request({
              url: "users/wxlogin",
              method: "POST",
              data: data
        })
  },
}


//定单接口
const myApi = {
  //创建订单接口
      /**
   * 1. 创建订单
   *    1. 请求地址 /my/orders/create
   *    2. 请求方式POST
   *    3. 请求参数
   *          1. 请求头 Authorization  token
   *          2. order_price,consignee_addr,goods
   */
  createOrder: function(data){
        return request({
              url: "my/orders/create",
              method: "POST",
              data: data
        })
  },
  //获取支付参数
  reqUnifiedorder: function(data){
        return request({
              url: "my/orders/req_unifiedorder",
              method: "POST",
              data: data
        })
  },
  //查看订单支付状态
  checkOrder: function(data){
        return request({
              url: "my/orders/chkOrder",
              method: "POST",
              data: data,
              header: {a:123}
        })
  },
}




const API = {
  homeApi,
  categoriesApi,
  goodsApi,
  usersApi,
  myApi
}


export default API


// export default request

